package com.comp6231.replica1.server;

import java.io.FileNotFoundException;
import java.io.PrintWriter;

import org.omg.CORBA.ORB;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAHelper;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.PortableServer.POAPackage.ObjectNotActive;
import org.omg.PortableServer.POAPackage.ServantAlreadyActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;

import java.util.ArrayList;
import java.util.List;

import com.comp6231.replica1.data.Stations;

/**
 * 
 * @author sknarula (narula.sk@gmail.com)
 * @since October 2013
 * 
 *        This is the DPIS server system's main class This class creates the
 *        instances of server and starts the servers
 * 
 */
public class StationServerSystem implements Runnable {

	/**
	 * @throws InvalidName
	 * @throws WrongPolicy
	 * @throws ServantAlreadyActive
	 * @throws ObjectNotActive
	 * @throws FileNotFoundException
	 * @throws AdapterInactive
	 */
	public void run() {
		/**
		 * Array list of server instances to be instantiated every time the
		 * system starts
		 */
		List<StationServerImplementation> servers = new ArrayList<StationServerImplementation>();

		// instantiate and save the servers stations in array list
		for (Stations station : Stations.values()) {
			servers.add(new StationServerImplementation(station
					.getPoliceStationType()));
		}

		// bind the server into orb object
		ORB orb = ORB.init(new String[] { "" }, null);
		try {
			POA rootPOA = POAHelper.narrow(orb
					.resolve_initial_references("RootPOA"));
			for (StationServerImplementation server : servers) {
				byte[] id = rootPOA.activate_object(server);

				org.omg.CORBA.Object ref = rootPOA.id_to_reference(id);

				String ior = orb.object_to_string(ref);

				PrintWriter file = new PrintWriter(
						System.getProperty("user.dir")
								+ "/src/com/comp6231/replica1/server/"
								+ server.getStationName() + "Ior.txt");
				file.println(ior);
				file.close();

				rootPOA.the_POAManager().activate();

				System.out
						.println(server.getStationName() + " server is ready");

				// start the UPD thread for this server
				new StationServerToServerInterface(server).start();
			}
			orb.run();
		} catch (InvalidName | ServantAlreadyActive | WrongPolicy
				| ObjectNotActive | FileNotFoundException | AdapterInactive e) {
			e.printStackTrace();
		}
	} // end of main method

}
